package com.isyscore.os;

import com.isyscore.boot.mqtt.MqttTemplate;
import com.isyscore.boot.mqtt.QoS;
import com.isyscore.os.mqtt.MqttCustomer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.time.LocalDateTime;

@SpringBootApplication
@EnableScheduling
@Slf4j
public class App {
    @Autowired
    private MqttTemplate mqttTemplate;
    @Autowired
    private MqttCustomer mqttCustomer;
    @Value("${to-os-topic:}")
    private String sendToServerTopic;
    @Value("${subscribe-os-topic:}")
    private String serverSendTopic;

    public static void main( String[] args ) {
        SpringApplication.run(App.class,args);
    }

    /**
     * 设备端订阅指令集平台下发的指令
     */
    @PostConstruct
    public void init(){
        mqttTemplate.subscribe(receivedMessage -> mqttCustomer.deal(receivedMessage),serverSendTopic, QoS.AT_MOST_ONCE);
    }

    /**
     * 设备主动上报数据demo
     */
    @Scheduled(cron = "0/10 0/1 * * * ? ")
    public void mockMqttProducer(){

        log.info(">>>每隔10秒上报设备数据到os平台");
        String sendMsg = "{\"operate\":\"ATTR_UP\",\"operateId\":1,\"data\":[{\"pk\":\"A0118010000\",\"devId\":\"A011801-00042\",\"time\":1598433697087,\"params\":{\"WIND_SPEED\":\""+LocalDateTime.now().getSecond()+"\"}}]}";
        mqttTemplate.publishAsync(sendToServerTopic,sendMsg.getBytes(Charset.defaultCharset()),QoS.AT_MOST_ONCE);
    }
}
